import { FriendType } from "../components/Member";
import { MessageType } from "../components/Message";
import { RoomType } from "../components/Room";

export function mergeRoomMessage(message: MessageType, rooms: RoomType[], isSelf = false) {
    return rooms.map((room: RoomType) => {
        if(message.receiverId === room.id) {
            let { messages = [], ...base } = room;
            if(typeof message?.memoId === 'undefined') {
                if(!isSelf) {
                    if(typeof base?.unread === 'undefined') {
                        base.unread = 0;
                    }
                    base.unread++;
                }
                messages = [...(messages), message];
            }
            else {
                const {memoId, ...income} = message;
                messages = messages.map((item) => {
                    if(item.id === memoId) {
                        return income;
                    }
                    return item;
                });
            }
            return { ...base, messages };
        }
        return room;
    });
}
export function mergeFriendMessage(message: MessageType, firends: FriendType[], isSelf = false) {
    return firends.map((friend: FriendType) => {
        if(message.chatId === friend.chatId) {
            let { messages = [], ...base } = friend;
            if(typeof message?.memoId === 'undefined') {
                if(!isSelf) {
                    if(typeof base?.unread === 'undefined') {
                        base.unread = 0;
                    }
                    base.unread++;
                }
                messages = [...(messages), message];
            }
            else {
                const {memoId, ...income} = message;
                messages = messages.map((item) => {
                    if(item.id === memoId) {
                        return income;
                    }
                    return item;
                });
            }
            return { ...base, messages };
        }
        return friend;
    });
}

